import docx


class ConfigParser(object):
    def __init__(self, config_path):
        self.doc = docx.Document(config_path)
        self.txt, self.tbl, self.pic = self.parse()

    def parse(self):
        doc_txt, doc_tbl, doc_pic = [], [], []
        tables = self.doc.tables
        pic_num = 0

        for line in self.doc.paragraphs:
            text = line.text.strip()
            if not text:
                continue
            key, value = (x.strip() for x in text.split(':', 1))

            if key == 'para':
                para = value
            elif key == 'type':
                type = value
            elif key == 'field':
                field = value
            elif key == 'desc':
                if type == 'table':
                    table = tables.pop(0)
                    desc = [[cell.text for cell in row.cells] for row in table.rows]
                    doc_txt.append((para, type, field, desc))
                    doc_tbl.append((para, type, field, desc))  # TODO 使用反射方法优化
                elif type == 'pic':
                    pic_num += 1
                    desc = F'image{pic_num}.jpeg'
                    doc_pic.append((para, type, field, desc))
                else:
                    desc = value
                    doc_txt.append((para, type, field, desc))

        return doc_txt, doc_tbl, doc_pic


if __name__ == '__main__':
    config_path = r'./data/doc/Test_doc_temp.docx'
    cfg = ConfigParser(config_path)
